import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    SectionList,
    TouchableOpacity,
    AsyncStorage,
    StatusBar,
    DeviceEventEmitter,
    Platform
} from 'react-native';
import {ListRow, SearchInput,Drawer,Theme} from 'teaset';
const {height, width} = Dimensions.get('window');
import {Toast,ModalIndicator} from 'teaset';
import Utils from'../../common/Utils'
import Config from '../../common/Config'
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
export default class NewFriendPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/directories/getFriendRequest',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    alert(JSON.stringify(re))
                    this.setState({
                        data:responseJson.data
                    })
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            token:'',
            data:[]
        }
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="black"
                    barStyle="light-content"/>
                <View style={styles.titleView}>
                    <TouchableOpacity
                        onPress={()=>Actions.pop()}
                        style={styles.goBackView}>
                        <Image
                            source={ImageUtil.WhiteGoBack}
                            style={styles.goBackImg}/>
                    </TouchableOpacity>
                    <Text style={styles.titleMsg}>新的朋友</Text>
                    <TouchableOpacity
                        onPress={()=>Actions.AddFriendPage()}
                        style={styles.completeView}>
                        <Text style={[styles.titleMsg]}>添加好友</Text>
                    </TouchableOpacity>
                </View>
                <TouchableOpacity
                    onPress={()=>Actions.QueryFriendsPage()}
                    style={{justifyContent:'center',alignItems:'center'}}>
                    <View style={styles.searchInput}>
                        <Image source={ImageUtil.Search}/>
                        <Text style={{fontSize:14,color:'#646464',marginLeft:12}}>搜索</Text>
                    </View>
                </TouchableOpacity>
                <SectionList
                    ItemSeparatorComponent={this.line}
                    renderSectionHeader={ (section) => this.sectionComp(section) }
                    renderItem={ (item ,index) => this.renderItem(item,index) }
                    keyExtractor={ (item) => item.name }
                    sections={ this.state.data }/>
            </View>
        );
    }

    line=()=>{
        return(
            <View style={{height:1,width:width,backgroundColor:'#ffffff'}}>
                <View style={{height:1,width:width-15,backgroundColor:'#e3e3e4',marginLeft:15}}/>
            </View>
        )
    };

    sectionComp=(section)=>{
        return (
            <View>
                <View style={styles.iconView}>
                    <Text style={styles.iconMsg}>{section.section.name}</Text>
                </View>
                <View style={{height:1,width:width,backgroundColor:'#e3e3e4'}}/>
            </View>
        )
    };

    renderItem=(item,index)=>{
        return (
            <View style={styles.labelView}>
                <View style={styles.labelBottomView}>
                    <Image
                        source={{uri:'http://106.14.209.177/upload/'+item.item.head}}
                        style={styles.headImg}/>
                    <View style={{marginLeft:23}}>
                        <Text style={styles.nameMsg}>{item.item.name}</Text>
                        <Text style={styles.introductionMsg}>{item.item.msg}</Text>
                    </View>
                    {this.status(item)}
                </View>
                {item.item.id==item.section.data[item.section.data.length-1].id
                ?(<View style={{width:width,height:1,backgroundColor:'#e3e3e4'}}/>)
                :null}
            </View>
        )
    };

    accept=(id)=>{
        let params={
            "token":this.state.token,
            "coverId":id
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/directories/addFrinden',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    DeviceEventEmitter.emit('refresherHead','qqqq');
                    this.getInfo();
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    status=(item)=>{
        if(item.item.status===0){
            return(
                <TouchableOpacity
                    onPress={()=>this.accept(item.item.userId)}
                    style={styles.ButView}>
                    <Text style={styles.ButMsg}>接受</Text>
                </TouchableOpacity>
            )
        }else if(item.item.status===1){
            return (
                <View style={styles.ButChangeView}>
                    <Text style={styles.ButChangeMsg}>已添加</Text>
                </View>
            )
        }else if(item.item.status===2){
            return(
                <View style={styles.ButChangeView}>
                    <Text style={styles.ButChangeMsg}>已过期</Text>
                </View>
            )
        }
    };

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#000000',
        width:width,
        alignItems:'center',
        justifyContent:'center',
        height:Platform.OS==='ios'?64:44
    },
    titleMsg:{
        fontSize:17,
        color:'#ffffff',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    goBackView:{
        position: 'absolute',
        top:Platform.OS==='ios'?65/2:25/2,left:15,
    },
    goBackImg:{
        height:18,
        width:18
    },
    completeView:{
        position: 'absolute',
        right:15,bottom:0
    },
    searchInput:{
        width:width-30,
        height:29,
        borderWidth:1,
        borderColor:'#e3e3e4',
        marginTop:12,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:5,
        backgroundColor:'#ffffff'
    },
    iconView:{
        height:24,
        justifyContent:'center'
    },
    iconMsg:{
        fontSize:12,
        color:'#646464',
        marginLeft:15
    },
    labelView:{
        // height:67,
        width:width,
        backgroundColor:'#ffffff',
        borderColor:'#e3e3e4',
        // borderBottomWidth:1,
        // borderTopWidth:1
    },
    labelBottomView:{
        height:67,
        width:width,
        flexDirection:'row',
        alignItems:'center'
    },
    headImg:{
        height:44,
        width:44,
        borderRadius:5,
        marginLeft:15
    },
    nameMsg:{
        fontSize:13,
        color:'#000000'
    },
    introductionMsg:{
        marginTop:13,
        fontSize:13,
        color:'#646464'
    },
    searchInputView:{
        marginTop:12,
        alignItems:'center'
    },
    ButView:{
        position: 'absolute',
        right:15,
        backgroundColor:'#3090dd',
        height:26,
        width:44,
        borderRadius:5,
        alignItems:'center',
        justifyContent:'center'
    },
    ButMsg:{
        fontSize:13,
        color:'#ffffff',
        textAlign:'center'
    },
    ButChangeView:{
        position: 'absolute',
        right:15,
        height:26,
        width:44,
        alignItems:'center',
        justifyContent:'center'
    },
    ButChangeMsg:{
        fontSize:13,
        color:'#646464',
        textAlign:'center'
    },
    titleImg:{
        height:20,
        width:20
    },
    titleImgView:{
        position:'absolute',
        bottom:27/2,right:15
    },
});
